package com.edt.ichannel.api.service.impl;

import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.json.IceFastJsonUtils;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.entiy.local.*;
import com.edt.ichannel.api.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 计算佣金服务类
 * @author 孙梁
 * 2018/6/13 13:48
 */
@Service
public class BonusServiceImpl implements BonusService {
    private Logger logger = LogManager.getLogger(BonusServiceImpl.class);
    @Resource
    private ProductService productService;
    @Resource
    private BalanceProductService balanceProductService;

    @Resource
    private ExpansionService expansionService;


    @Resource
    private BonusRuleService bonusRuleService;
    @Resource
    private QuanYBonusRuleService quanYBonusRuleService;
    @Resource
    private BonusLogService bonusLogService;

    @Resource
    private OrderCreditService orderCreditService;


    @Resource
    private StaffService staffService;
    @Resource
    private WorpOrderService worpOrderService;
    @Resource
    private MechanismsService mechanismsService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void setBonus(OrderCredit orderCredit) {
        if (orderCredit != null) {
            String productId = productService.getProductIdByCode(orderCredit.getProductCode());
            if (balanceProductService.isBalanceProduce(productId)) {
                //判断订单是人还是渠道的
                String orderType = worpOrderService.getOrderType(orderCredit.getOrderCode());
                //是人，则是0级订单
                if(!CommonConstant.ORDER_TYPE_STAFF.equals(orderType)){
                    String expansionId = worpOrderService.getChannelIdByOrderCode(orderCredit.getOrderCode());
                    Expansion expansion = expansionService.getExpansionById(expansionId);
                    if (expansion != null) {
                        Staff staff = staffService.getStaffById(expansion.getStaffId());
                        String staffId = null;
                        if(staff != null){

                            if(CommonConstant.STAFF_TYPE_ZY == staff.getType()){
                                staffId = staff.getId();

                            }else if(CommonConstant.STAFF_TYPE_QUANY == staff.getType()){
                                Mechanisms mechanisms = mechanismsService.selectMechanismsById(staff.getOrgId());
                                if(mechanisms.getStaffState() == CommonConstant.STAFF_STATE_HAS){
                                    staffId = mechanisms.getStaffId();
                                }
                            }
                            if(IceStringUtils.isNotBlank(staffId)){
                                expansion.setStaffId(staffId);
                                BonusRule bonusRule = null;
                                if(CommonConstant.STAFF_TYPE_QUANY == expansion.getType()){
                                    QuanYBonusRule quanYBonusRule = quanYBonusRuleService.getBonusRule(productId, orderCredit.getCityCode(), orderCredit.getFirstMoney());
                                    if (quanYBonusRule != null) {
                                        bonusRule = new BonusRule();
                                        BeanUtils.copyProperties(quanYBonusRule,bonusRule);
                                    }
                                }else{
                                    bonusRule = bonusRuleService.getBonusRule(productId, orderCredit.getCityCode(), orderCredit.getFirstMoney());
                                }
                                if (bonusRule != null) {
                                    updateBounsData(orderCredit, expansion, bonusRule);
                                } else {
                                    logger.info("没有查询到发展奖规则：orderCode--->" + orderCredit.getOrderCode());
                                }
                            }
                        }
                    } else {
                        logger.info("没有查询到小微渠道：orderCode--->" + orderCredit.getOrderCode());
                    }
                }

            } else {
                logger.info("没有查询到结算商品:productId--->" + productId);
            }

        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateBounsData(OrderCredit orderCredit, Expansion expansion, BonusRule bonusRule) {

        if (orderCredit != null && expansion != null && bonusRule != null) {
            BonusLog bonusLog = new BonusLog();
            bonusLog.setExpansionId(expansion.getId());
            bonusLog.setBonusDate(new Date());
            bonusLog.setBonusMoney(bonusRule.getBonusMoney());
            bonusLog.setOrderCode(orderCredit.getOrderCode());
            bonusLog.setStaffId(expansion.getStaffId());
            bonusLog.setFirstMoney(orderCredit.getFirstMoney());
            bonusLog.setFirstBonusMoney(bonusRule.getBonusMoney());
            bonusLog.setBonusFirstMoneyUp(bonusRule.getFirstMoneyUp());
            bonusLog.setBonusFirstMoneyDown(bonusRule.getFirstMoneyDown());

            //佣金是0 也要记一次流水，避免没有佣金的数据每次都要计算
            orderCredit.setBonusMoney(bonusRule.getBonusMoney());
            orderCreditService.upadateOrderCteditBonusMoney(orderCredit);
            Staff staff = staffService.getStaffById(expansion.getStaffId());
            logger.debug("拓展人： " + expansion.getStaffId() + "查询拓展人账户：" + IceFastJsonUtils.toJsonString(staff));
            if (staff != null) {
                staffService.addStaffAccountMoney(bonusRule.getBonusMoney(), expansion.getStaffId());
                staffService.addStaffBonusMoney(bonusRule.getBonusMoney(),expansion.getStaffId());
            }
            bonusLog.setBonusState(CommonConstant.BONUS_LOT_STATE_SUCCESS);
            bonusLogService.saveBonusLog(bonusLog);
        }
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void putoutBounsSupperadd(CommissionSuperadd commissionSuperadd) {
        if (commissionSuperadd != null && commissionSuperadd.getBonusMoney() > 0) {
            Expansion expansion = expansionService.getExpansionById(commissionSuperadd.getChannelId());
            if(expansion != null){
                BonusLog bonusLog = new BonusLog();
                bonusLog.setExpansionId(commissionSuperadd.getChannelId());
                bonusLog.setBonusDate(new Date());
                bonusLog.setBonusMoney(commissionSuperadd.getBonusMoney().intValue());
                bonusLog.setOrderCode(commissionSuperadd.getOrderCode());
                bonusLog.setStaffId(expansion.getStaffId());
                Staff staff = staffService.getStaffById(expansion.getStaffId());
                logger.debug("拓展人： " + expansion.getStaffId() + "查询拓展人账户：" + IceFastJsonUtils.toJsonString(staff));
                if (staff != null) {
                    staffService.addStaffAccountMoney(commissionSuperadd.getBonusMoney().intValue(), expansion.getStaffId());
                    staffService.addStaffBonusMoney(commissionSuperadd.getBonusMoney().intValue(),expansion.getStaffId());
                }
                bonusLog.setBonusState(CommonConstant.BONUS_LOT_STATE_SUCCESS);
                bonusLogService.saveBonusLog(bonusLog);
            }

        }
    }


}
